package com.gcsoftware.utils;

import com.gcsoftware.authentications.helper.ShiroUtils;
import com.gcsoftware.gw.TokenInfo;
import com.gcsoftware.web.beans.T_GW_APPS;
import com.gcsoftware.web.beans.T_GW_APP_IPS;
import com.gcsoftware.web.beans.response.GetTokenRsp;
import com.gcsoftware.web.threads.TokenThread;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.UUID;

/**
 * Created by qs on 2018/4/14.
 */
public class TokenUtils {

    public static final int INVALID_APP_ID=40013;
    public static final int INVALID_APP_SECRET=40014;
    public static final int UNFOUND_APP_ID=40003; //缺少appid
    public static final int UNFOUND_APP_SECRET=40004; //缺少secret参数

    public static GetTokenRsp generateToken(T_GW_APPS appInfo, List<String> ips) {
        String token = genToken(appInfo.getC_APP_ID());
        setTokenToRedis(token,appInfo,ips);
        GetTokenRsp rsp = new GetTokenRsp();
        rsp.setErrCode(0);
        rsp.setAppToken(token);
        rsp.setExpiresIn(7200);
        return rsp;
    }
    private static String genToken(String appId) {
        String token = UUID.randomUUID().toString().replace("-","");
        token = ShiroUtils.sha256(token,appId);
        return token;
    }
    private static void setTokenToRedis(String token, T_GW_APPS appInfo, List<String> ips) {
        TokenInfo info = new TokenInfo();
        info.setToken(token);
        info.setAppId(appInfo.getC_APP_ID());
        info.setAppName(appInfo.getC_APP_NAME());
        info.setRoleId(appInfo.getC_ROLE_ID());
        info.setRoleName(appInfo.getC_ROLE_NAME());
        info.setAppIps(ips);
        //getStringRedis().boundValueOps((TOKEN_ROLE_PREFIX + token).getBytes()).set(SerializationUtils.serialize(info), 7200);
        TokenThread.setTokenQue(info);
    }
}
